package cn.edu.nuc.crm.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.nuc.crm.dao.CartMapper;
import cn.edu.nuc.crm.dao.ProductMapper;
import cn.edu.nuc.crm.entity.Cart;
import cn.edu.nuc.crm.entity.Product;
import cn.edu.nuc.crm.service.interfaces.CartService;

@Service
public class CartServiceImpl implements CartService {
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private ProductMapper productMapper;
	
	
	public Cart detail( int cartid){
		
		Cart cart = cartMapper.selectByPrimaryKey(cartid);
		return cart;
		
	}
	
	
	
	
	@Transactional
	public int insert(Cart cart) {
		int result = cartMapper.insert(cart);
		return result;
	}
	@Override
	public List<Cart> cartlist() {
		List<Cart> cartlist =  cartMapper.cartlist();
		return cartlist;
	}
	@Override
	public int deleteByPrimaryKey(Integer cartid) {
		int result=cartMapper.deleteByPrimaryKey(cartid);
		return result;
	}
	
	
	@Transactional(propagation = Propagation.REQUIRED, // 事务传播行为
	noRollbackFor = { NullPointerException.class }, // 当发生这些异常时,不回滚事务
	rollbackFor = { SQLException.class }, // 当发生这些异常时,回滚事务
	timeout = 20, // 超时. 当此事务耗时达到20秒时,结束此事务
	isolation = Isolation.READ_COMMITTED // 设置隔离级别。 未设置以数据库隔离级别为准
)
	public int cleanCart() throws Exception	
	{	
		int count;
		List<Cart> cartlist = new ArrayList<Cart>();
		cartlist = cartMapper.cartlist();
			for(int i=0;i<cartlist.size();i++){
				Product pro = new Product();
				pro = productMapper.selectByPrimaryKey(cartlist.get(i).getProductid());
				pro.setProductid(cartlist.get(i).getProductid());			
				pro.setProductnum(pro.getProductnum()-cartlist.get(i).getCartnum());
				productMapper.updateByPrimaryKeySelective(pro);
				if(pro.getProductnum()-cartlist.get(i).getCartnum()<0)
					throw new Exception ("123");
             count = cartMapper.deleteByPrimaryKey(cartlist.get(i).getCartid());		
        }
			count = 1;
			return count;
	  }

}
